/*
 * @Author: yangy
 * @Date: 2023-12-22 12:46:06
 * @LastEditors: yangy
 * @LastEditTime: 2023-12-22 12:49:00
 * @FilePath: /admin_vue3_element_plus/src/utils/useTabList.js
 * @Description:
 *
 * Copyright (c) 2023 by 青柠利合科技(北京)有限公司, All Rights Reserved.
 */
import { ref } from "vue";
import { useRoute, onBeforeRouteUpdate } from "vue-router";
import { useCookies } from "@vueuse/integrations/useCookies";
import { router } from "@/router";

export function useTabList() {
  const route = useRoute();
  const cookie = useCookies();
  const activeTab = ref(route.path);
  const tabList = ref([
    {
      title: "后台首页",
      path: "/",
    },
  ]);
  //添加标签导航
  function addTab(tab) {
    // 表示标签导航中没有这个标签

    // 通过findIndex的方法使用就可以拿到回调对象t, 将每个回调对象通过t.path
    // 拿到每个对象的path值, 将每个对象的path值与传过来的tab对象中的path做对比
    let noTab = tabList.value.findIndex((t) => t.path == tab.path) == -1;
    // -1 表示没有找到, 没有找到表示之前没有添加过了
    if (noTab) {
      tabList.value.push(tab);
    }
    cookie.set("tabList", tabList.value);
  }

  // 初始化标签导航列表
  function initTabList() {
    let tbs = cookie.get("tabList");
    if (tbs) {
      tabList.value = tbs;
    }
  }

  initTabList();

  // 路由更新前
  onBeforeRouteUpdate((to, from) => {
    activeTab.value = to.path;
    addTab({
      title: to.meta.title,
      path: to.path,
    });
  });

  // 切换标签栏触发的函数,进行页面跳转
  const changeTab = (t) => {
    activeTab.value = t;
    router.push(t);
    // console.log(t)
  };

  // 关闭标签栏导航,触发的函数
  // 关闭标签栏,激活下一个或者上一个标签,
  const removeTab = (t) => {
    let tabs = tabList.value;
    let a = activeTab.value;
    if (a == t) {
      tabs.forEach((tab, index) => {
        if (tab.path == t) {
          // const netxTab = tabs[index+1] || tabs[index-1] || 0
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            a = nextTab.path;
          }
        }
      });
    }
    activeTab.value = a;
    // 进行过滤, 只要不等于当前关闭的这个标签就会被留下来, 最后更新cookie
    // 符合条件的过滤掉,不符合条件的留下来
    tabList.value = tabList.value.filter((tab) => tab.path != t);
    cookie.set("tabList", tabList.value);
  };

  const handleClose = (c) => {
    if (c == "clearAll") {
      // 表示清除所有,切换回首页
      activeTab.value = "/";
      // 过滤只剩下首页
      tabList.value = [
        {
          title: "后台首页",
          path: "/",
        },
      ];
    } else if (c == "clearOther") {
      tabList.value = tabList.value.filter(
        (tab) => tab.path == "/" || tab.path == activeTab.value
      );
    }
    cookie.set("tabList", tabList.value);
  };

  return { activeTab, tabList, changeTab, removeTab, handleClose };
}
